import os
from serial_disk_gui import SerialDiskGUI
from serial_disk_cli import SerialDiskCLI
from log_manager import LogManager
from error_handler import ErrorHandler

class SerialDiskApp:
    @staticmethod
    def create_gui_app(config_path=None):
        """创建GUI应用实例"""
        if config_path is None:
            config_path = os.path.join(
                os.path.dirname(__file__),
                'config.json'
            )
        return SerialDiskGUI(config_path)
        
    @staticmethod
    def create_cli_app(config_path=None):
        """创建CLI应用实例"""
        if config_path is None:
            config_path = os.path.join(
                os.path.dirname(__file__),
                'config.json'
            )
        return SerialDiskCLI(config_path)

def main():
    """主程序入口"""
    import argparse
    
    # 初始化日志
    log_manager = LogManager()
    
    try:
        parser = argparse.ArgumentParser(description='Serial Disk 文件传输工具')
        parser.add_argument('--cli', action='store_true',
                           help='使用命令行界面')
        parser.add_argument('--config', type=str,
                           help='配置文件路径')
        
        args = parser.parse_args()
        
        if args.cli:
            app = SerialDiskApp.create_cli_app(args.config)
        else:
            app = SerialDiskApp.create_gui_app(args.config)
            
        try:
            app.start()
        except KeyboardInterrupt:
            LogManager.info("程序被用户中断")
        except Exception as e:
            ErrorHandler.handle_device_error(e)
        finally:
            app.stop()
            
    except Exception as e:
        LogManager.exception("程序启动失败")
        return 1
        
    return 0

if __name__ == '__main__':
    exit(main()) 